package app.auto.designer.view;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;

import android.widget.ListView;
import android.widget.Toast;

import com.example.TestPlugin.asset.Apk;
import com.example.TestPlugin.asset.Apk;
import com.example.TestPlugin.asset.AssetCopyer;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import app.auto.designer.R;
import app.auto.designer.permission.PermissionActivity;
import app.auto.designer.tool.LayoutDrawable;
import app.auto.runner.base.Prt;
import app.auto.runner.base.action.ViewInflater;
import app.auto.runner.base.framework.CrashHandler;
import app.auto.runner.base.utility.ReadFileUtil;
import app.auto.runner.base.utility.ScreenSchema;
import app.auto.runner.base.utility.StorageUtil;
import app.auto.runner.base.utility.WriteFileUtil;
import app.auto.runner.base.MapViewConf;
import app.auto.runner.base.RRes;
import app.auto.runner.base.SPrefUtil;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.ListBuilder;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.intf.json.JsonUtil;
import app.auto.runner.base.ui.MoveView;
import app.auto.runner.base.utility.ShareAlert;
import app.auto.runner.base.DialogUtil;
import app.auto.runner.base.utility.ToastUtil;

import static android.view.View.VISIBLE;
import static android.view.ViewGroup.FOCUS_AFTER_DESCENDANTS;


public class ViewActivity extends PermissionActivity {

    public List attrinParent = ListBuilder.build().add("orientation").add("weightSum").get();

    public View focused;
    public ViewGroup focusedGroup;
    public View topview;
    private FunCallback doubleClick_2;
    private long mExitTime;

    public ViewGroup getTopview() {
        return (ViewGroup) topview;
    }

    private ListView listview;
    private Map map;
    private FunCallback func;
    private String txt;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PgyCrashManager.register(this);
        PgyUpdateManager.register(this);
        ScreenSchema.init(this);
        CrashHandler.getInstance().init(this);
//        ToastUtil.live(this).toast("======== dpi "+getResources().getDisplayMetrics().densityDpi);

        func = new FunCallback() {
            @Override
            public void simpleRun(Object aty) {
                super.simpleRun(aty);
                try {

                    if (attrPopupWd != null) {
                        dismissPopup(attrPopupWd);

                    }
                    attrPopupWd = bottomSlide(ViewActivity.this, getCurrentFocus());

                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        };

        txt = ReadFileUtil.readres(this, R.raw.attr);
//        setCallback(func);
        setContentView(R.layout.auto_edit);

        topview = getGroup(R.id.bench).getChildAt(0);
        func.setParam(topview);
        setClick();
        doubleClick_2 = new FunCallback() {
            @Override
            public void simpleRun(Object aty) {
                func.setParam(aty).simpleRun(getCurrentFocus());

//                func.setParam(getCurrentFocus()).simpleRun(func.getObject());
//                        startActivity(new Intent(ViewActivity.this, FuncListActivity.class));
            }
        };
        //        initGesture();
//        if (TextUtils.isEmpty(stringcontent)) {
//        String stringcontent = getIntent().getStringExtra("stringcontent");
//        String path = Environment.getExternalStorageDirectory() + "/" + "adesign/try.xml";
        String path =
                (String) SPrefUtil.getValue("filecontext", "currfile", String.class);
        if (!TextUtils.isEmpty(path)) {
            objfilepath = path;
            clearAssembleView(path);
        } else {
            clearAssembleView(null);
        }


//        setGroupFocused((ViewGroup) topview);
//        setFocused(topview);
//        getView(R.id.addope).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                getTopview().addView(new LinearLayout(v.getContext()));
//            }
//        });
//        getView(R.id.addope).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                getTopview().addView(new LinearLayout(v.getContext()));
//            }
//        });

        initGesture();
        //暂时注释
//        getView(R.id.up).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (focused.getParent() == null || focused.getParent() != getTopview()) {
//
//                } else {
//                    setFocused((ViewGroup) focused.getParent());
//                }
//            }
//        });
//        getView(R.id.left).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (focused.getParent() == null) {
//
//                } else {
//                    ViewGroup vg = (ViewGroup) focused.getParent();
//                    int i = vg.indexOfChild(focused);
//                    if (i == 0) {
//
//                    } else {
//                        setFocused(vg.getChildAt(i - 1));
//                    }
//                }
//            }
//        });
//
//        getView(R.id.right).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (focused.getParent() == null) {
//
//                } else {
//                    ViewGroup vg = (ViewGroup) focused.getParent();
//                    int i = vg.indexOfChild(focused);
//                    if (i == vg.getChildCount() - 1) {
//
//                    } else {
//                        setFocused(vg.getChildAt(i + 1));
//                    }
//                }
//            }
//        });
//
//        getView(R.id.down).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                try {
//                    if (!(focused instanceof ViewGroup) || ((ViewGroup) focused).getChildCount() == 0) {
//
//                    } else {
//                        setFocused(((ViewGroup) focused).getChildAt(0));
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });


    }

    public void clearAssembleView(String path) {
        getTopview().removeAllViews();
        focused = null;
        focusedGroup = null;
        String stringcontent;
        if (path == null) {
            stringcontent = getIntent().getStringExtra("stringcontent");
        } else
            stringcontent = ReadFileUtil.readsd(this, path);

//        }
        stringcontent = stringcontent.replaceAll("\"", "\"");
        if (!TextUtils.isEmpty(stringcontent)) {
            try {
                Parser.withActivity(ViewActivity.this).parse(stringcontent, ((ViewGroup) getGroup(R.id.content)), null);
            } catch (Exception e) {
                CrashHandler.errorDialog(e);
                e.printStackTrace();
            }
        }

        visitViews(getTopview().getChildAt(0), false);
        getTopview().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                doubleClick_2.setParam(v).simpleRun(getCurrentFocus());
                return false;
            }
        });

    }

    private void setClick() {
        getView(R.id.nav).setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                navView();
            }
        });
        getView(R.id.navgrp).setOnLongClickListener(new View.OnLongClickListener() {
            @SuppressLint("NewApi")
            @Override
            public boolean onLongClick(View v) {
                try {
                    isdashlineFrame = !isdashlineFrame;
                    visitViews(getTopview().getChildAt(0), isdashlineFrame);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
        getView(R.id.navgrp).setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                try {

                    nextGroupFocus(focusedGroup, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView(R.id.navpre).setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                try {

                    int idx = tiviews.indexOf(focused);
                    if (focused.getForeground() != null) {


                        if (idx == 0) {
                            idx = tiviews.size() - 1;
                        } else {
                            idx--;
                        }
                    } else {
                        clearfGroupFocused();
                    }
                    setFocused(tiviews.get(idx));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        getView(R.id.add).setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                try {

                    int idx = tiviews.indexOf(focused);
                    if (focused.getForeground() != null) {

                        if (idx == 0) {
                            idx = tiviews.size() - 1;
                        } else {
                            idx--;
                        }
                    } else {
                        clearfGroupFocused();
                    }
                    setFocused(tiviews.get(idx));


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AssetCopyer.with(ViewActivity.this).copy();

            }
        }, 3000);
        click(R.id.addview, new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View view) {
                if (getCurrentFocus() == null || getCurrentFocus().getParent() == null) {
                    setGroupFocused((ViewGroup) getTopview().getChildAt(0));
                    return;
                }
                if (focused != null && focused.getForeground() != null) {
                    setGroupFocused((ViewGroup) focused.getParent());
                    clearbeforeFocused = focused;
                    clearFocused();
                    target_add_dialog = DialogUtil.showDialog(view, R.color.theme_color, ListBuilder.build().add("LinearLayout").add("RelativeLayout").add("ScrollView").add("TextView").add("ImageView").add("Button").add("CheckBox").add("RadioButton").add("ListView").add("GridView").add("android.support.v4.widget.SwipeRefreshLayout").add("复制").get(), addclicklistener);
                    return;
                }
                if (focusedGroup == null || focusedGroup.getForeground() == null) {
                    getView(R.id.navgrp).performClick();
                    return;
                }

                target_add_dialog = DialogUtil.showDialog(view, R.color.theme_color, ListBuilder.build().add("LinearLayout").add("RelativeLayout").add("ScrollView").add("TextView").add("ImageView").add("Button").add("CheckBox").add("RadioButton").add("ListView").add("GridView").add("android.support.v4.widget.SwipeRefreshLayout").add("复制").get(), addclicklistener);

            }
        });

        getView(R.id.addview).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (getCurrentFocus() != null) {
                    delAlert(getCurrentFocus());

                }
                return false;
            }
        });

    }

    protected void navView() {
        try {

            int idx = tiviews.indexOf(focused);
            if (focused == null || focused.getForeground() != null) {

                if (idx == tiviews.size() - 1) {
                    idx = 0;
                } else {
                    idx++;
                }

            }
            clearfGroupFocused();
            setFocused(tiviews.get(idx));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    View clearbeforeFocused;

    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    public String rmIdLine(String tag, String contain, String replacement) {
        return replaceLine(tag, "android:id", "");
    }

    public String replaceLine(String tag, String contain, String replacement) {
        if (tag.contains(replacement)) {
            return tag;
        } else {
            boolean added = false;
            String output = "";
            for (String l : tag.split("\n")) {
                if (!contain.equals("") && l.contains(contain.split("\\:")[1])) {
                    output += replacement + "\n";
                    added = true;
                } else {
                    output += l + "\n";
                }
            }
            if (!added) {
                output = output.replace("/>", replacement + "/>");
            }
            tag = output;
        }
        return tag;
    }


    final AdapterView.OnItemClickListener addclicklistener = new AdapterView.OnItemClickListener() {
        @SuppressLint("WrongConstant")
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            addView(adapterView.getItemAtPosition(i).toString(), view);
//dimension integer float ref string
        }


    };

    protected void addView(String viewname,View view) {
        String name = viewname;

//            if (isContainChinese(name)) {
//                return;
//            }
        if (target_add_dialog != null) {
            target_add_dialog.dismiss();
            target_add_dialog.cancel();

        }
        String absname = "";
        String basexml = null;
        if (name.equals("复制")) {
            absname = clearbeforeFocused.getClass().getName();

        } else if (!name.equals("View")) {
            absname = "android.widget." + name;
        }
        if (name.equals("复制")) {
            Parser.ProduceView pv =
                    setXmltoView((String) clearbeforeFocused.getTag(R.id.xml));
            view = pv.getView();
            basexml = (String) clearbeforeFocused.getTag(R.id.xml);
            basexml = rmIdLine(basexml, "android:id", "");

        } else {
            try {
                view = (View) Class.forName(absname)
                        .getConstructor(Context.class)
                        .newInstance(ViewActivity.this);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        int width = -2;
        int height = -2;
        if (view instanceof ViewGroup) {
            width = -1;
            height = -1;
//                            view.setBackgroundResource(R.drawable.auto_background_rect_yellow_addchild);
        }

        ListBuilder layoutbuilder = ListBuilder.build().add("FrameLayout").add("AbsoluteLayout").add("LinearLayout").add("RelativeLayout");
        ViewGroup layoutseek = focusedGroup;
        while (!layoutbuilder.get().contains(layoutseek.getClass().getSimpleName())) {
            if (layoutseek.getParent() != null) {

                layoutseek = (ViewGroup) focusedGroup.getParent();
            } else {
                return;
            }
        }

        String paramName = layoutseek.getClass().getName() + "$LayoutParams";
        if (focusedGroup instanceof AdapterView) {
            paramName = ViewGroup.class.getName() + "$LayoutParams";
        }
        ViewGroup.MarginLayoutParams params = null;
        try {
            params = (ViewGroup.MarginLayoutParams) Class.forName(paramName)
                    .getConstructor(int.class, int.class)
                    .newInstance(width, height);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        view.setLayoutParams(params);
        try {
            focusedGroup.addView(view, focusedGroup.indexOfChild(clearbeforeFocused) + 1);
        } catch (Exception e) {
            if (e.getMessage().contains("can host only one direct child")) {
                new AlertDialog.Builder(ViewActivity.this).setMessage(e.getMessage()).show();
                return;
            }
        }


        if (view instanceof ViewGroup
                && !(view instanceof AdapterView)
                ) {
            if (basexml == null) {
            basexml = getBaseXml(view, "fill_parent", "fill_parent");
        }
            if (view instanceof LinearLayout) {
                basexml = replaceLine(basexml, "", "android:orientation=\"vertical\"\n");
                ((LinearLayout) view).setOrientation(LinearLayout.VERTICAL);
            }
            grviews.clear();
            visitViews(getTopview().getChildAt(0), false);
            setGroupFocused((ViewGroup) view);
            view.setTag(R.id.xml, basexml);
        } else {if (basexml == null) {
            basexml = getBaseXml(view, "wrap_content", "wrap_content");
        }
            Integer count = labelsCount.get(view.getClass().getName());
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            labelsCount.put(view.getClass().getName(), count);
            if (view instanceof TextView) {
                ((TextView) view).setText(view.getClass().getSimpleName() + count);

                basexml = replaceLine(basexml, "android:text", "android:text=\"" + view.getClass().getSimpleName() + count + "\"\n");
            } else if (view instanceof ImageView) {
                Drawable bm = getResources().getDrawable(R.drawable.ic_launcher, null);
                view.getLayoutParams().width = bm.getIntrinsicWidth();
                view.getLayoutParams().height = bm.getIntrinsicHeight();
                ((ImageView) view).setImageDrawable(bm);
                basexml = replaceLine(basexml, "android:src", "android:src=\"@drawable/ic_launcher\"\n");
            } else if (view instanceof ListView) {
                String taginner = "fake:[[item1,test1],[item2,test2],[item3,test2]];layout:auto_string_item_adapt";
                String tag =
                        "android:tag=\"" + taginner
                                + "\"\n";
                basexml = replaceLine(basexml, "", tag);
                ViewInflater.tagrateListView(view, taginner, ViewActivity.this);
//                    Drawable bm = getResources().getDrawable(R.drawable.ic_launcher, null);
//                    view.getLayoutParams().width = bm.getIntrinsicWidth();
//                    view.getLayoutParams().height = bm.getIntrinsicHeight();
//                    ((ImageView) view).setImageDrawable(bm);
//                    basexml = replaceLine(basexml, "android:src", "android:src=\"@drawable/ic_launcher\"\n");
            } else if (view instanceof GridView) {
                String taginner = "fake:[[item1,test1],[item2,test2],[item3,test2]];layout:auto_string_item_adapt";
                String tag =
                        "android:tag=\"" + taginner
                                + "\"\n";
                basexml = replaceLine(basexml, "", tag);

                basexml = replaceLine(basexml, "", "android:numColumns=\"3\"\n");
                ((GridView) view).setNumColumns(3);
                ViewInflater.tagrateListView(view, taginner, ViewActivity.this);
//                    Drawable bm = getResources().getDrawable(R.drawable.ic_launcher, null);
//                    view.getLayoutParams().width = bm.getIntrinsicWidth();
//                    view.getLayoutParams().height = bm.getIntrinsicHeight();
//                    ((ImageView) view).setImageDrawable(bm);
//                    basexml = replaceLine(basexml, "android:src", "android:src=\"@drawable/ic_launcher\"\n");
            } else {
                View bckgroundview = LayoutInflater.from(ViewActivity.this).inflate(R.layout.layout_add_background_label, null);
                ((TextView) bckgroundview.findViewById(R.id.label)).setText(view.getClass().getSimpleName() + count);
                LayoutDrawable.LayoutToDrawable(bckgroundview, view, ViewActivity.this);
                view.setTag(R.id.uiflag, "true");
            }
            tiviews.clear();
            visitViews(getTopview().getChildAt(0), false);
            setFocused(view);
            clearfGroupFocused();
            view.setTag(R.id.xml, basexml);

//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {

//
//                                }
//                            }, 500);

        }
    }


    final AdapterView.OnItemClickListener addRootclicklistener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String name = adapterView.getItemAtPosition(i).toString();
            if (isContainChinese(name)) {
                return;
            }
            if (target_add_dialog != null) {
                target_add_dialog.dismiss();
                target_add_dialog.cancel();
            }
            String absname = "";
            if (!name.equals("View")) {
                absname = "android.widget." + name;
            }
            try {
                view = (View) Class.forName(absname)
                        .getConstructor(Context.class)
                        .newInstance(ViewActivity.this);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int width = -2;
            int height = -2;
            if (view instanceof ViewGroup) {
                width = -2;
                height = -2;
//                            view.setBackgroundResource(R.drawable.auto_background_rect_yellow_addchild);
            }

            String paramName = "android.widget.RelativeLayout$LayoutParams";
            ViewGroup.MarginLayoutParams params = null;
            try {
                params = (ViewGroup.MarginLayoutParams) Class.forName(paramName)
                        .getConstructor(int.class, int.class)
                        .newInstance(width, height);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            view.setLayoutParams(params);
            getTopview().addView(view, getTopview().getChildCount() - 1);
            String basexml;

            if (view instanceof ViewGroup) {
                basexml = getBaseXml(view, "fill_parent", "fill_parent");
                if (view instanceof LinearLayout) {
                    basexml = replaceLine(basexml, "", "android:orientation=\"vertical\"\n");
                    ((LinearLayout) view).setOrientation(LinearLayout.VERTICAL);
                }
                grviews.clear();
                visitViews(getTopview().getChildAt(0), false);
                setGroupFocused((ViewGroup) view);
                view.setTag(R.id.xml, basexml);
            } else {
                basexml = getBaseXml(view, "wrap_content", "wrap_content");
                Integer count = labelsCount.get(view.getClass().getName());
                if (count == null) {
                    count = 1;
                } else {
                    count++;
                }
                labelsCount.put(view.getClass().getName(), count);
                if (view instanceof TextView) {
                    ((TextView) view).setText(view.getClass().getSimpleName() + count);
                } else if (view instanceof ImageView) {
                    Drawable bm = ContextCompat.getDrawable(ViewActivity.this, R.drawable.ic_launcher);
                    view.getLayoutParams().width = bm.getIntrinsicWidth();
                    view.getLayoutParams().height = bm.getIntrinsicHeight();
                    ((ImageView) view).setImageDrawable(bm);
                } else if (view instanceof ListView) {
                    String taginner = "fake:[[item1,test1],[item2,test2],[item3,test2]];layout:auto_string_item_adapt";
                    String tag =
                            "android:tag=\"" + taginner
                                    + "\"\n";
                    basexml = replaceLine(basexml, "", tag);
                    ViewInflater.tagrateListView(view, taginner, ViewActivity.this);
//                    Drawable bm = getResources().getDrawable(R.drawable.ic_launcher, null);
//                    view.getLayoutParams().width = bm.getIntrinsicWidth();
//                    view.getLayoutParams().height = bm.getIntrinsicHeight();
//                    ((ImageView) view).setImageDrawable(bm);
//                    basexml = replaceLine(basexml, "android:src", "android:src=\"@drawable/ic_launcher\"\n");
                } else if (view instanceof GridView) {
                    String taginner = "fake:[[item1,test1],[item2,test2],[item3,test2]];layout:auto_string_item_adapt";
                    String tag =
                            "android:tag=\"" + taginner
                                    + "\"\n";
                    basexml = replaceLine(basexml, "", tag);

                    basexml = replaceLine(basexml, "", "android:numColumns=\"3\"\n");
                    ((GridView) view).setNumColumns(3);
                    ViewInflater.tagrateListView(view, taginner, ViewActivity.this);
//                    Drawable bm = getResources().getDrawable(R.drawable.ic_launcher, null);
//                    view.getLayoutParams().width = bm.getIntrinsicWidth();
//                    view.getLayoutParams().height = bm.getIntrinsicHeight();
//                    ((ImageView) view).setImageDrawable(bm);
//                    basexml = replaceLine(basexml, "android:src", "android:src=\"@drawable/ic_launcher\"\n");
                } else {
                    View bckgroundview = LayoutInflater.from(ViewActivity.this).inflate(R.layout.layout_add_background_label, null);
                    ((TextView) bckgroundview.findViewById(R.id.label)).setText(view.getClass().getSimpleName() + count);
                    LayoutDrawable.LayoutToDrawable(bckgroundview, view, ViewActivity.this);
                    view.setTag(R.id.uiflag, "true");
                }
                tiviews.clear();
                visitViews(getTopview().getChildAt(0), isdashlineFrame);
                setFocused(view);
                clearfGroupFocused();
                view.setTag(R.id.xml, basexml);
//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {

//
//                                }
//                            }, 500);
            }
//dimension integer float ref string
        }


    };


    public String getBaseXml(View view, String s, String s1) {
        String xml = "";
        String ns = " xmlns:android=\"http://schemas.android.com/apk/res/android\"";
//            xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n";
        xml += "<" + view.getClass().getSimpleName() + ns + "\n";
        xml += "android:layout_width=\"" + s + "\"\n";
        xml += "android:layout_height=\"" + s1 + "\"\n";
        xml += "/>";
        return xml;
    }

    Map<String, Integer> labelsCount = new TreeMap<String, Integer>();

    private void addViewGroupFocused(ViewGroup view) {

        for (int i = focusedGroup.getChildCount() - 1; i > 0; i--) {
            View c = focusedGroup.getChildAt(i);
            if (c instanceof ViewGroup) {
                int jj;
                if ((jj = grviews.indexOf((ViewGroup) c)) != -1) {
                    grviews.add(jj + 1, view);
                }
            }
        }
        int ii = grviews.indexOf(focusedGroup);
        grviews.add(ii + 1, view);
    }

    List<View> addViews = new ArrayList<View>();

    String objfilepath;

    public void backexit() {

        final Dialog dialog = DialogUtil.showDialog(getTopview(), R.color.theme_color, ListBuilder.build().add(objfilepath).add("功能").add("新建").add("打开").add("保存").add("保存&退出").add("另存为").add("分享").get(), new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Object item = adapterView.getItemAtPosition(i);
                if (item.toString().contains("新建")) {
                    if (objfilepath != null && objfilepath.contains("design/tmp")) {
                        turnWhile(getTopview(), saveas(objfilepath));
                        ShareAlert.sureAlert(ViewActivity.this, "已为您保存为\n" + objfilepath, new FunCallback() {
                            @Override
                            public void simpleRun(Object aty) {
                                super.simpleRun(aty);
                                newpath();
                                DialogUtil.cancelDialog();
                            }


                        });
                    } else {
                        newpath();
                        DialogUtil.cancelDialog();
                    }

                } else {
                    DialogUtil.cancelDialog();
                    if (item.toString().contains("打开")) {
                        new LFilePicker().withActivity(ViewActivity.this)
                                .withRequestCode(open).withMutilyMode(false).withIconStyle(Constant.ICON_STYLE_BLUE).withTitle("Open").start();
//                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                        intent.setType("text/plain");//设置类型，我这里是任意类型，任意后缀的可以这样写。
//                        intent.addCategory(Intent.CATEGORY_OPENABLE);
//                        intent.putExtra("action", "open");
//                        startActivityForResult(intent, 0);
                    } else if (item.toString().contains("另存为")) {
//                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                        intent.setType("text/plain");//设置类型，我这里是任意类型，任意后缀的可以这样写。
//                        intent.addCategory(Intent.CATEGORY_OPENABLE);
//                        intent.putExtra("action", "saveas");
//                        startActivityForResult(intent, 1);

                        new LFilePicker().withActivity(ViewActivity.this)
                                .withRequestCode(saveas).withMutilyMode(false).withIconStyle(Constant.ICON_STYLE_BLUE).withTitle("Save as").start();
                    } else if (item.toString().contains("保存")) {
                        if (objfilepath == null) {
                            new LFilePicker().withActivity(ViewActivity.this)
                                    .withRequestCode(save).withMutilyMode(false).withIconStyle(Constant.ICON_STYLE_BLUE).withTitle("Save").start();

                        } else {
                            turnWhile(getTopview(), saveas(objfilepath));

                        }
                    }

                    if (item.toString().contains("退出")) {

                        finish();
                    } else if (item.toString().contains("返回")) {
                    } else if (item.toString().contains("分享")) {

                        FunCallback funCallback = turnWhile(getTopview(), saveas(objfilepath));
                        if (funCallback != null) {
                            ToastUtil.live(ViewActivity.this).toast("已为您保存文件内容");
                            ShareAlert.shareAlert(ViewActivity.this, funCallback.getResult().toString(), "分享文件", new FunCallback() {
                                        @Override
                                        public void simpleRun(Object aty) {
                                            super.simpleRun(aty);
                                            Intent shareIntent = new Intent();
                                            shareIntent.setAction(Intent.ACTION_SEND);
                                            shareIntent.addCategory("android.intent.category.DEFAULT");
                                            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(objfilepath)));
                                            shareIntent.setType("application/txt");
                                            startActivity(Intent.createChooser(shareIntent, "分享"));
                                        }
                                    }
                            );

                        }
                    } else if (item.toString().contains("功能")) {

                        startActivity(new Intent(ViewActivity.this, FunListActivity.class));

                    }
                }

            }
        });
        dialog.getWindow().getDecorView().setTag(R.id.tag_flag, "退出窗");
        DialogUtil.setCurrentDialog(dialog);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0) {
                    exit();
                }
                return true;
            }
        });
    }

    protected void newpath() {
        String design = StorageUtil.getPrimaryStoragePath(ViewActivity.this) + "/design";
        if (!new File(design).exists()) {
            new File(design).mkdirs();
        }
        int j = 1;

        File f;
        f = new File(design + "/" + "tmp" + (new File(design).list().length + j) + ".xml");
        while (f.exists()) {
            j++;
            f = new File(design + "/" + "tmp" + (new File(design).list().length + j) + ".xml");
        }
        if (j == 1) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            objfilepath = f.getAbsolutePath();
            clearAssembleView(objfilepath);
            target_add_dialog = showAddRoot(ViewActivity.this, R.color.theme_color, ListBuilder.build().add("为新界面添加根元素").add("LinearLayout").add("RelativeLayout").add("ScrollView").add("TextView").add("ImageView").add("Button").add("CheckBox").add("RadioButton").add("ListView").add("GridView").add("android.support.v4.widget.SwipeRefreshLayout").get(), addRootclicklistener);
        }
    }

    public static Dialog showAddRoot(Activity ctx, int linecolor, List<String> liststring, AdapterView.OnItemClickListener onitemclicklistener) {
        DialogUtil.DialogInfo du = new DialogUtil.DialogInfo(ctx);
        final ListView listview;
        du.aty = ctx;
        du.view = listview = new ListView(ctx);
        listview.setBackgroundResource(linecolor);
        String big = "";
        for (String s : liststring) {
            big += ",[" + s +
                    "]";
        }
        big = big.substring(1);
        listview.setTag("fake:[" +
                big + "];layout:");
        MapViewConf.with(ctx).source(liststring
                , listview).conf(MapViewConf.with(ctx).source(com.aliang.auto.R.layout.auto_string_item)).toView();
        du.neutralButtonClickListener = new DialogUtil.DialogClicker();
        listview.setOnItemClickListener(onitemclicklistener);

        Dialog dialog = DialogUtil.showNeutralDialog(du, false);
        DialogUtil.setCurrentDialog(dialog);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
        listview.performItemClick(null, 2, 0);

            }
        },100);
        return dialog;
    }

    @NonNull
    public FunCallback saveas(String path) {
        if (path == null) {
            ToastUtil.live(this).toast("尚未有保存地址");
            return new FunCallback() {
                @Override
                public Object getResult() {
                    return super.getResult();
                }
            };
        }
        final File file = new File(path);
        return new FunCallback() {
            Map<String, String> vgs = new TreeMap<String, String>();

            @Override
            public void simpleRun(Object aty) {
                super.simpleRun(aty);

//                                    if (((View) aty) instanceof ViewGroup) {
//
//                                    } else {
                String v;
                if (((View) aty) instanceof ViewGroup && !(((View) aty) instanceof AdapterView)) {
                    v = vgs.get(((View) aty).toString());

                } else {
                    v = (String) ((View) aty).getTag(R.id.xml);
                }
                String g = (String) ((View) ((View) aty).getParent()).getTag(R.id.xml);
                if (v != null) {
                    if (((View) aty) != getTopview().getChildAt(0)) {
                        v = v.replace("xmlns:android=\"http://schemas.android.com/apk/res/android\"", "");
                    }
                } else {
                    v = "";
                }
                if (g != null) {
                    if (((View) aty).getParent() != getTopview().getChildAt(0)) {
                        g = g.replace("xmlns:android=\"http://schemas.android.com/apk/res/android\"", "");
                    }
                    if (!vgs.containsKey(((View) ((View) aty).getParent()).toString())) {
                        vgs.put(((View) ((View) aty).getParent()).toString(), ((String) ((View) ((View) aty).getParent()).getTag(R.id.xml)).replace("/>", ">"));
                    }
                    String t = vgs.get(((View) ((View) aty).getParent()).toString());
                    if (!t.contains(v)) {
                        t += "\n" + v;
                        vgs.put(((View) ((View) aty).getParent()).toString(), t);

                    }

                    if (((ViewGroup) ((View) aty).getParent()).indexOfChild((View) aty) == ((ViewGroup) ((View) aty).getParent()).getChildCount() - 1) {

                        t = vgs.get(((View) ((View) aty).getParent()).toString());
                        t += "\n</" + ((String) ((View) ((View) aty).getParent()).getClass().getSimpleName()) + ">";
                        vgs.put(((View) ((View) aty).getParent()).toString(), t);
                        if (((ViewGroup) ((View) aty).getParent()) == getTopview().getChildAt(0)) {
//                                                ShareAlert.shareAlert((Activity) ((View) aty).getContext(), t);
                            String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";

                            if (!t.contains(xml)) {
                                t = xml + t;
                            }
                            setResult(t);
                            WriteFileUtil.writeTxtToFile(t, file.getParent(), file.getName());
                            DialogUtil.cancelDialog();
                        }
                    }
                }


//                                    }
            }
        };
    }

    public final int open = 0;
    public final int saveas = 1;
    public final int save = 2;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
            List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);

            if (requestCode == open) {
                if (list != null) {
                    if (list.size() > 0) {
                        String p = list.get(0);
                        clearAssembleView(p);
                        objfilepath = p;

                    }
                    return;
                }

                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);

                if (actualimagecursor == null) {
                    ToastUtil.live(this).toast("不支持此文件传输方式目前");
                    return;
                }
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                String img_path = actualimagecursor.getString(actual_image_column_index);
                clearAssembleView(img_path);
                objfilepath = img_path;
            } else if (requestCode == saveas) {
                if (list != null) {
                    if (list.size() > 0) {
                        String p = list.get(0);
                        turnWhile(getTopview(), saveas(p));

                    }
                    return;
                }
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);

                if (actualimagecursor == null) {
                    ToastUtil.live(this).toast("不支持此文件传输方式目前");
                    return;
                }
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                String img_path = actualimagecursor.getString(actual_image_column_index);
                File file = new File(img_path);
                turnWhile(getTopview(), saveas(file.getAbsolutePath()));

            } else if (requestCode == save) {
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);

                if (actualimagecursor == null) {
                    ToastUtil.live(this).toast("不支持此文件传输方式目前");
                    return;
                }
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                String img_path = actualimagecursor.getString(actual_image_column_index);
                File file = new File(img_path);
                turnWhile(getTopview(), saveas(file.getAbsolutePath()));
                objfilepath = file.getAbsolutePath();
            }
        }
    }

    public FunCallback turnWhile(ViewGroup vgroup, FunCallback funcallback) {

        for (int i = 0; i < vgroup.getChildCount(); i++) {
            View v = vgroup.getChildAt(i);
            if (v instanceof ViewGroup) {
                turnWhile((ViewGroup) v, funcallback);
            }
            funcallback.simpleRun(v);
            if (funcallback.getResult() != null) {
                return funcallback;
            }
        }
        return null;
    }

    @TargetApi(Build.VERSION_CODES.M)
    @SuppressLint("NewApi")
    public void nextGroupFocus(ViewGroup viewgroup, Boolean next) {
        focusedGroup = viewgroup;
        int idx = grviews.indexOf(focusedGroup);
        if (next != null) {
            if (!next) {

            }
        } else {
            if (focusedGroup == null || focusedGroup.getForeground() != null) {


                if (idx == grviews.size() - 1) {
                    idx = 0;
                } else {
                    idx++;
                }

            }
        }
        clearFocused();
        setGroupFocused(grviews.get(idx));
    }


    @Override
    protected void onResume() {
        super.onResume();
        ((MoveView) getView(R.id.navlt)).setContext(this);
    }

    FunCallback viewGestureFunc = new FunCallback() {
        @Override
        public void simpleRun(Object aty) {
            super.simpleRun(aty);
            //singleGesture
            if (getObject() != null) {
                clicktask((View) getObject());
            }
        }
    };

    boolean gesSingleFlag;
    private GestureDetector mGestureDetector;
    private int verticalMinDistance = 180;
    private int minVelocity = 0;

    private void initGesture() {
        mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {


            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                gesSingleFlag = true;

                boolean rt = super.onSingleTapUp(e);
                return rt;
            }


            @Override
            public boolean onDoubleTap(MotionEvent e) {
                if (focused != null) {
                    View adap = focused;
                    while ((adap.getParent() instanceof View) && adap.getParent() != null && !(((View) adap.getParent()) instanceof AdapterView)) {
                        adap = (View) adap.getParent();
                    }
                    if (adap.getParent() instanceof AdapterView) {
                        setFocused((View) adap.getParent());
                        clearfGroupFocused();
                    }
                }
                doubleClick_2.simpleRun(focused);

                return super.onDoubleTap(e);
            }
        });
    }

    View.OnTouchListener touch;

    private void setViewTouch(final View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
//
//        view.setOnTouchListener(null);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mGestureDetector.onTouchEvent(event);
                if (gesSingleFlag) {
                    gesSingleFlag = false;
                    clicktask(v);
                }
                return false;
            }
        });

    }

    View.OnTouchListener touchListener = new View.OnTouchListener() {
        public int mMoveY;
        public int mMoveX;
        public static final int MAX_MOVE_FOR_CLICK = 8;
        public static final long MAX_LONG_PRESS_TIME = 650;
        public long mSecondClick;
        public long mFirstClick;
        public int mDownY;
        public int mUpY;
        public int mUpX;
        public Object mSingleClickTask;
        public long mLastUpTime;
        public int mDownX;
        public int mClickcount;
        public boolean isDoubleClick;
        public long mLastDownTime;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mLastDownTime = System.currentTimeMillis();
                    mDownX = (int) event.getX();
                    mDownY = (int) event.getY();
                    mClickcount++;
                    Log.e("mouse", "DOWN-->mClickcount=" + mClickcount + "; isDoubleClick=" + isDoubleClick);
                    if (mSingleClickTask != null) {
//                        mBaseHandler.removeCallbacks(mSingleClickTask);
                    }
                    if (!isDoubleClick)
                        ToastUtil.live(ViewActivity.this).toast("长按");
//                        mBaseHandler.postDelayed(mLongPressTask, MAX_LONG_PRESS_TIME);
                    if (1 == mClickcount) {
                        mFirstClick = System.currentTimeMillis();
                    } else if (mClickcount == 2) {// 双击
                        mSecondClick = System.currentTimeMillis();
                        if (mSecondClick - mFirstClick <= MAX_LONG_PRESS_TIME) {
                            //处理双击
                            isDoubleClick = true;
                            mClickcount = 0;
                            mFirstClick = 0;
                            mSecondClick = 0;
//                            mBaseHandler.removeCallbacks(mSingleClickTask);
//                            mBaseHandler.removeCallbacks(mLongPressTask);
                            Log.e("mouse", "double double double....");
                        }
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    mMoveX = (int) event.getX();
                    mMoveY = (int) event.getY();
                    int absMx = Math.abs(mMoveX - mDownX);
                    int absMy = Math.abs(mMoveY - mDownY);
                    Log.e("mouse", "MOVE-->absMx=" + absMx + "; absMy=" + absMy);
                    if (absMx > MAX_MOVE_FOR_CLICK && absMy > MAX_MOVE_FOR_CLICK) {
//                        mBaseHandler.removeCallbacks(mLongPressTask);
//                        mBaseHandler.removeCallbacks(mSingleClickTask);
                        isDoubleClick = false;
                        mClickcount = 0;//移动了
                    }
                    if (absMx >= 5 && absMy >= 5) {
                        //处理移动
                        isDoubleClick = false;
                        mClickcount = 0;//移动了
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    mLastUpTime = System.currentTimeMillis();
                    mUpX = (int) event.getX();
                    mUpY = (int) event.getY();
                    int mx = Math.abs(mUpX - mDownX);
                    int my = Math.abs(mUpY - mDownY);
                    Log.e("mouse", "UP-->mx=" + mx + "; my=" + my);
                    if (mx <= MAX_MOVE_FOR_CLICK && my <= MAX_MOVE_FOR_CLICK) {
                        if ((mLastUpTime - mLastDownTime) <= MAX_LONG_PRESS_TIME) {
//                            mBaseHandler.removeCallbacks(mLongPressTask);
                            if (!isDoubleClick)
                                ToastUtil.live(ViewActivity.this).toast("单击");
//                                mBaseHandler.postDelayed(mSingleClickTask, MAX_SINGLE_CLICK_TIME);
                        } else {
                            //超出了双击间隔时间
                            mClickcount = 0;

                        }
                    } else {
                        //移动了
                        mClickcount = 0;
                    }
                    if (isDoubleClick) isDoubleClick = false;
                    ToastUtil.live(ViewActivity.this).toast("双击");
                    taiqi();
                    break;
            }
            return true;
        }

        private void taiqi() {
        }
    };
    boolean isAttachToWindow;

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachToWindow = true;
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttachToWindow = false;
    }

    @SuppressLint("ResourceType")
    public PopupWindow bottomSlide(Context ctx, final View view) {
        if (view == null) {
            return null;
        }
        String rname = ((View) view).getClass().getSimpleName();
        final String name = "android.widget." + rname;


        Map attrs = new TreeMap();
        Parser.ProduceView pv;
        pv = setXmltoView((String) view.getTag(R.id.xml));

        attrs = pv.attrs;
        Map<String, Object> list = findAttrsContant(name, txt.replaceAll("\\/", "."));
        //view.class -> attr: type:xxx constant:xxx
        Map<String, Object> list_parent = new TreeMap<String, Object>();
        if (view.getParent() != null) {
            String psrentname = "android.view.ViewGroup$MarginLayoutParams";
            list_parent = findAttrsContant(psrentname, txt.replaceAll("\\/", "."));
            list.putAll(list_parent);
        }

        final Map map = sortHashMap(list, attrs, view);
        if (view.getParent() != null) {
            map.putAll(findAttrForChildInParent((ViewGroup) view.getParent(), attrs));
        }
        final List wlist = new ArrayList(map.values());
        String tag = (String) getCurrentFocus().getTag(R.id.xml);
        ListBuilder lb = ListBuilder.build();
        for (int i = 0; i < wlist.size(); i++) {
            Object m = wlist.get(i);
            String attr = (String) ((Map) m).get("attr");
            if (tag.contains(attr)) {
                ((Map) m).put("uiflag", "bold");
                lb.add(m);

            }
        }
        wlist.removeAll(lb.get());
        lb.get().addAll(wlist);
        final List maplist = lb.get();
        final ListView listview = new ListView(ctx);
        listview.setId(1);
        listview.setTag(rname);
        listview.setHeaderDividersEnabled(true);
        listview.setSmoothScrollbarEnabled(true);
        listview.setScrollContainer(true);
        listview.setBackgroundResource(R.color.theme_color);
        listview.setTag(R.id.tag_data, maplist);
        final BaseAdapter badapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return data.size();
            }

            @Override
            public Object getItem(int position) {
                return data.get(position);
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(final int position, final View convertView, ViewGroup parent) {
                View convert = null;
                final Map m = (Map) getItem(position);
                try {

                    if (m.get("type") == null) {
                        convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_constant, null);

                    } else {
                        ListBuilder rel = ListBuilder.build().add("layout_alignBaseline").add("layout_alignBottom").add("layout_alignEnd").add("layout_alignLeft").add("layout_alignRight").add("layout_alignStart").add("layout_alignTop").add("layout_toStartOf").add("layout_toEndOf").add("layout_toLeftOf").add("layout_toLeftOf").add("layout_toRightOf").add("layout_above").add("layout_below");
                        boolean b = false;
                        try {
                            b = rel.get().contains(m.get("attr").toString().replace("android:", ""));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (b) {

                            convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_constant, null);
                            MapBuilder mapbuilder = MapBuilder.build();
                            for (int i = 0; i < ((ViewGroup) getCurrentFocus().getParent()).getChildCount(); i++) {
                                View view = ((ViewGroup) getCurrentFocus().getParent()).getChildAt(i);
                                String idstring = (String) view.getTag(R.id.tag_id);
                                if (idstring != null) {
                                    mapbuilder.add(view.getId() + "", idstring);
                                }
                            }

                            m.put("constant", mapbuilder.get());
                            m.put("type", "constant");
                            m.put("uivalue", "[  Id  ]");
                        }
                        if (m.get("type").toString().contains("string")) {
                            convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_string, null);
                            ((EditText) convert.findViewById(R.id.input)).addTextChangedListener(new TextWatcher() {

                                @Override
                                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                }

                                @Override
                                public void onTextChanged(CharSequence s, int start, int before, int count) {

                                }

                                @Override
                                public void afterTextChanged(Editable s) {
                                    m.put("value", s.toString());

                                    effectonView(popupWindow);
                                }
                            });
                        } else if (m.get("type").toString().contains("integer")) {
                            convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_integer, null);
                        } else if (m.get("type").toString().contains("dimension")) {
                            convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_dimension, null);
                            ((RadioButton) convert.findViewById(R.id.reference)).setButtonDrawable(R.drawable.radio);
                            ((RadioButton) convert.findViewById(R.id.dimension)).setButtonDrawable(R.drawable.radio);
                            ((RadioButton) convert.findViewById(R.id.constant)).setButtonDrawable(R.drawable.radio);
                            final View finalConvert1 = convert;
                            ((EditText) convert.findViewById(R.id.input)).addTextChangedListener(new TextWatcher() {
                                @Override
                                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                }

                                @Override
                                public void onTextChanged(CharSequence s, int start, int before, int count) {

                                }

                                long input;

                                @Override
                                public void afterTextChanged(Editable s) {
                                    updateEffectonDimension(s);


                                }

                                public void updateEffectonDimension(final Editable s) {
                                    if (input != 0) {
                                        if (System.currentTimeMillis() - input > 1000L) {
                                            if (((Button) finalConvert1.findViewById(R.id.attr_unit)).getVisibility() == View.VISIBLE) {
                                                String number = s.toString();
                                                number += ((Button) finalConvert1.findViewById(R.id.attr_unit)).getText().toString();
                                                m.put("value", number);

                                            }
                                            effectonView(popupWindow);
                                        } else {
                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    updateEffectonDimension(s);
                                                }
                                            }, 1000);
                                        }
                                    } else {
                                        input = System.currentTimeMillis();
                                    }
                                }
                            });
                        } else if (m.get("type").toString().contains("boolean")) {
                            m.put("constant", MapBuilder.build().add("0", "true").add("1", "false").get());
                            m.put("type", "constant");
                            m.put("uivalue", "[ Bool  ]");
                            convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_constant, null);
                        } else if (m.get("type").toString().contains("constant")) {
                            convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_constant, null);
                            if (!m.containsKey("uivalue")) {
                                m.put("uivalue", "[ Cons ]");
                            }
                        }
                        if (m.get("type").toString().contains("reference")) {
                            if (convert == null) {
                                convert = LayoutInflater.from(ViewActivity.this).inflate(R.layout.attr_constant, null);
                            }
                            if (m.get("type").toString().contains("constant")) {

                            } else {
                                String[] types = m.get("type").toString().split("|");
                                if (types.length == 2) {
                                    convert.findViewById(R.id.attr_constant).setVisibility(View.VISIBLE);
                                } else if (types.length == 1) {
                                    convert.findViewById(R.id.attr_constant).setVisibility(View.INVISIBLE);
                                }
                            }

                        }
                    }
                    //引用 ref
                    //id ref

                    /////constant 开始
                    if (m.get("type") == null) {
                        convert.findViewById(R.id.attr_constant).setVisibility(View.GONE);
                    } else if (m.get("type").toString().contains("constant")) {
//                                         m.get("type").toString().contains("constant");
                        convert.findViewById(R.id.attr_constant).setVisibility(VISIBLE);
                        final View finalView = convert;
                        final View finalConvert = convert;
                        convert.findViewById(R.id.attr_constant).setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                final Map<String, String> constant = (Map<String, String>) m.get("constant");


                                constantD = DialogUtil.showDialog(v, R.color.theme_color, new ArrayList<String>(constant.values()), new AdapterView.OnItemClickListener() {

                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                                        for (String k : constant.keySet()) {
                                            String val = constant.get(k);
                                            if (((TextView) v.findViewById(R.id.name)).getText().equals(val)) {
                                                ((TextView) finalView.findViewById(R.id.attr_constant)).setText(val);

//                                                String lineattr = m.get("attr").toString() + "=\"" + val + "\"";
//                                                m.put("linetext", lineattr);
                                                m.put("value", val);
                                                m.put("value_int", k + "");
                                                effectonView(popupWindow);
                                            }

                                        }
                                        constantD.cancel();
                                        constantD.dismiss();
                                    }
                                });
                            }
                        });
                        if (m.containsKey("value")) {
                            String value = m.get("value").toString();
                            ((TextView) convert.findViewById(R.id.attr_constant)).setText(value.toLowerCase());


                        } else {
                            String uivalue = "Default";
                            if (m.containsKey("uivalue")) {
                                uivalue = (String) m.get("uivalue");
                            }
                            ((TextView) convert.findViewById(R.id.attr_constant)).setText(uivalue);

                        }
                    } else if (m.get("type").toString().contains("dimension")) {
//                                         m.get("type").toString().contains("constant");
//                        convert.findViewById(R.id.input).setVisibility(VISIBLE)
                        String val = (String) m.get("value");
                        if (val != null && val.toLowerCase().contains("p")) {
                            String lowerval = val.toLowerCase().replace("dip", "")
                                    .replace("dp", "").replace("sp", "").replace("pt", "").replace("px", "");
                            String unit = val.replace(lowerval, "");

                            ((TextView) convert.findViewById(R.id.input)).setText(lowerval);
                            ((TextView) convert.findViewById(R.id.attr_unit)).setText(unit);

                        }
                        final View finalView = convert;
                    } else if (m.get("type").toString().contains("string")) {
                        String val = (String) m.get("value");
                        ((TextView) convert.findViewById(R.id.input)).setText(val);
                    } else {
//                        convert.findViewById(R.id.attr_constant).setVisibility(View.GONE);
                    }


                    /////constant 结束


                } catch (Exception e) {
                    e.printStackTrace();
                    CrashHandler.errorDialog(e);

                }
                ((TextView) convert.findViewById(R.id.attr_name)).setText(m.get("attr").toString().replace("android:", ""));

                //记录值 valuerecord 显示

                if (m.containsKey("uiflag")) {
                    String uiflag = (String) m.get("uiflag");
                    if (uiflag.equals("bold")) {
                        setGroupInTextViewBold((ViewGroup) convert);
                    }
                }


                return convert;
            }

            List data = maplist;

            @Override
            public void notifyDataSetChanged() {
                data = (List) listview.getTag(R.id.tag_data);
                super.notifyDataSetChanged();
            }
        };

//        HandlerUtil.sendEmptymessage(this, new FunCallback() {
//            @Override
//            public void simpleRun(Object aty) {
//                super.simpleRun(aty);
//            }
//        });
        listview.setAdapter(badapter);
        //                       MapViewConf.build().pair("xxx->yyy", "0:jiong;1:jun", "onclick:finish").source(R.layout.attr_constant);


        popupWindow = BottomPopupWindow.slideBottom(ViewActivity.this, listview, view, tabselectCallback);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                popupWindow.setAnimationStyle(R.style.slide_from_bottom);

                effectonView(popupWindow);
            }
        });
        return popupWindow;
    }

    FunCallback tabselectCallback = new FunCallback() {
        @Override
        public void simpleRun(Object aty) {
            super.simpleRun(aty);

        }
    };

    protected void setGroupInTextViewBold(ViewGroup convert) {
        for (int i = 0; i < convert.getChildCount(); i++) {
            View view = convert.getChildAt(i);
            if (view instanceof ViewGroup) {

            } else if (view instanceof TextView) {
                ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            }
        }
    }

    @Nullable
    protected Parser.ProduceView setXmltoView(String tag) {
        Parser.ProduceView pv = null;
        if (TextUtils.isEmpty((CharSequence) tag)) {

        } else {
            try {
                pv = Parser.withActivity(ViewActivity.this).parse((String) tag, null, null).setTosettag(false).getProduceView();

            } catch (Exception e) {
                ShareAlert.shareAlert(this, e.getCause() + "" + e.getMessage());
//                e.printStackTrace();
            }
        }
        return pv;
    }

    PopupWindow popupWindow;

    public void effectonView(PopupWindow popupWindow) {
        if (popupWindow == null) {
            return;
        }
        String width = "android:layout_width=\"fill_parent\"\n";
        String height = "android:layout_height=\"fill_parent\"\n";
        String lines = "";
        Adapter adapter = ((Adapter) ((ListView) popupWindow.getContentView().findViewById(1)).getAdapter());
        String tag = (String) ((ListView) popupWindow.getContentView().findViewById(1)).getTag();
        for (int i = 0; i < adapter.getCount(); i++) {

            Map value_n_format = (Map) adapter.getItem(i);
            if (!TextUtils.isEmpty((CharSequence) value_n_format.get("value"))) {
                String lineattr = value_n_format.get("attr").toString() + "=\"" + value_n_format.get("value").toString() + "\"";

                if (tag.contains(value_n_format.get("attr").toString())) {
                    int idx = tag.indexOf("\n", tag.indexOf(value_n_format.get("attr").toString() + 1));
                    Prt prt = Prt.cat(value_n_format.get("attr").toString(), tag.substring(idx, idx + 2), tag);
                    tag = tag.replace(prt.getPrt(), lineattr);
                } else {
                    if (lines.contains(lineattr)) {

                    } else {
                        lines = "\n" + lineattr + lines;
                    }
                }
            }


        }

        String view_xml = "<" + tag + "\n" + lines + "/>";
        View viewfocused = getCurrentFocus();
        String focusedtag = "";
        if (viewfocused.getTag(R.id.xml) != null) {
            focusedtag = (String) viewfocused.getTag(R.id.xml);
        }
        if (focusedtag.contains("xml:")) {
            int index = focusedtag.indexOf("xml:");
            int postindex = focusedtag.indexOf(";", index);
            String xml;
            if (postindex == -1) {
                xml = focusedtag.substring(index);
            } else {
                xml = focusedtag.substring(index, postindex) + ";";
            }
            focusedtag = focusedtag.replace(xml, "");
        }

//                String toaddxml = view_xml;
//                focusedtag += "xml:";
//                focusedtag += toaddxml;
//                focusedtag += ";";
//                viewfocused.setTag(focusedtag);
//                view_xml = (String) getCurrentFocus().getTag(R.id.xml);
//                view_xml = view_xml.replace("<" + tag , "<" + tag  + "\n"+ "xmlns:android=\"http://schemas.android.com/apk/res/android\"");
//                ShareAlert.shareAlert(ViewActivity.this, view_xml);
//                Toast.makeText(, Toast.LENGTH_LONG).show();
//                flagBack(true);

        getCurrentFocus().setTag(R.id.xml, (view_xml));
        if (view_xml != null) {
            try {
                String xmlutf8 =
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
                String xml =
//                xmlutf8+
                        view_xml.replaceAll("\\<\\?xml version=\"1.0\" encoding=\"utf-8\"\\?\\>", "");
                Parser.withActivity(ViewActivity.this).parse(xml, (ViewGroup) getCurrentFocus().getParent(), getCurrentFocus());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void flagBack(Boolean backflag) {
        this.backflag = backflag;

    }

    public void dismissPopup(PopupWindow pop) {
        pop.dismiss();
        pop = null;
    }

    private void cloneviewto(View fromview, View tofocused) {
        Field[] fields = tofocused.getClass().getFields();
//        for (Field f : fields) {
//            boolean accessible = f.isAccessible();
//            f.setAccessible(true);
//
//            try {
//                f.set(tofocused, fromview.getClass().getField(f.getName()).get(fromview));
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            } catch (NoSuchFieldException e) {
//                e.printStackTrace();
//            }
//        }
        fields = tofocused.getClass().getDeclaredFields();
        for (Field f : fields) {
            boolean accessible = f.isAccessible();
            f.setAccessible(true);

            try {
                f.set(tofocused, fromview.getClass().getDeclaredField(f.getName()).get(fromview));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }

    Dialog target_add_dialog;
    Dialog constantD;

    private Map<String, Map> findAttrForChildInParent(View view, Map attrs) {

        Map<String, Object> m = JsonUtil.fromContent(txt);
        String viewname = null;
        Class clz = null;
        do {
            if (viewname == null) {
                viewname = view.getClass().getName().replaceAll("\\.", "/");
                clz = view.getClass();
            } else {
                viewname = clz.getSuperclass().getName().replaceAll("\\.", "/");
                clz = clz.getSuperclass();
            }
        }
        while (!m.containsKey(viewname));
        Map<String, Object> attrmap = (Map<String, Object>) m.get(viewname);
        Map<String, Map> mapList = new TreeMap<String, Map>();

        for (String attr : attrmap.keySet()) {
            Map a = (Map) attrmap.get(attr);
            if (view instanceof ViewGroup) {

                if (!attrinParent.contains(attr.replace("android:", ""))) {
                    mapList.put(attr, a);
                    a.put("view", view.getClass().getName());
                    a.put("attr", attr);
                    if (attrs.containsKey(attr.replace("android:", ""))) {
                        a.put("value", attrs.get(attr.replace("android:", "")));
                    }

                }
            }


        }
        return mapList;
    }

    private Map<String, Map> sortHashMap(Map<String, Object> list, Map attrs, View view) {
        Map<String, Map> mapList = new TreeMap<String, Map>();
        for (String viewname : list.keySet()) {
            Map<String, Map> map = (Map) list.get(viewname);
            for (String attr : map.keySet()) {
                Map a = map.get(attr);
                if (!(view instanceof AdapterView) && view instanceof ViewGroup && viewname.endsWith(view.getClass().getSimpleName())) {
                    if (attrinParent.contains(attr.replace("android:", ""))) {
                        a.put("view", viewname);
                        a.put("attr", attr);
                        if (attrs.containsKey(attr.replace("android:", ""))) {
                            a.put("value", attrs.get(attr.replace("android:", "")));
                        }
                        mapList.put(attr, a);
                    }
                } else {
                    a.put("view", viewname);
                    a.put("attr", attr);
                    if (attrs.containsKey(attr.replace("android:", ""))) {
                        a.put("value", attrs.get(attr.replace("android:", "")));
                    }
                    mapList.put(attr, a);
                }


            }
        }

        return mapList;
    }


    //模块市场
    //商业模块市场
    //android intent
    //
    private Map<String, Object> findAttrsContant(String rawname, String txt) {
        Map<String, Object> attrgroup = new TreeMap<String, Object>();
        try {
            Map<String, Object> m = JsonUtil.fromContent(txt);
            String name = rawname;
            Class clazz = null;
            boolean supered = false;
            while (true) {
                if (supered) {
                    if (clazz == null) {
                        break;
                    }
                }

                clazz = Class.forName(name);
                if (!m.keySet().contains(clazz.getName().replace("$", "."))) {
                    clazz = clazz.getSuperclass();
                    if (clazz == null) {
                        break;
                    } else {
                        name = clazz.getName();
                    }
                    if (clazz != null) {
                        continue;
                    } else {
                        break;
                    }
                } else {
                    Map attrmap = (Map) m.get(clazz.getName().replace("$", "."));

                    attrgroup.put(name.replace("$", "."), attrmap);
                    clazz = clazz.getSuperclass();
                    name = clazz.getName();
                    supered = true;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attrgroup;
    }

    //    public Drawable getLayerDrawable(){
//        Resources resources = getResources();
//        Drawable[] layers = new Drawable[2];
//        layers[0] = resources.getDrawable(R.drawable.white);
//        layers[1] = resources.getDrawable(R.drawable.logo_overlay);
//        LayerDrawable layerDrawable = new LayerDrawable(layers)
//        ((ImageView) findViewById(R.id.imageview)).setImageDrawable(layerDrawable);
//        return
//    }

    @SuppressLint("NewApi")
    public void setGroupFocused(ViewGroup viewgroup) {
        if (viewgroup == null) {
            return;
        }
        if (this.focusedGroup != null) {
            this.focusedGroup.setForeground(getForegroundGroup());

        }
        this.focusedGroup = viewgroup;
        viewgroup.setForeground(ContextCompat.getDrawable(getBaseContext(), R.drawable.auto_background_rect_yellow));
//        focusedGroup.setOnLongClickListener(new View.OnLongClickListener() {
//
//            @Override
//            public boolean onLongClick(View view) {
//                if (view != getCurrentFocus()) return false;
//
//                ShareAlert.delAlert((Activity) view.getContext(), new FunCallback() {
//                    @Override
//                    public void simpleRun(Object aty) {
//                        super.simpleRun(aty);
//                        ((ViewGroup) focusedGroup.getParent()).removeView(focusedGroup);
//
//                    }
//                });
//                return false;
//            }
//        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getStringExtra("action") != null) {
            if (intent.getStringExtra("action").toString().contains("del")) {
                delAlert(getCurrentFocus(), false);
            }
        }
    }

    @SuppressLint("NewApi")
    public void clearfGroupFocused() {
        if (focusedGroup != null) {
            this.focusedGroup.setForeground(getForegroundGroup());

        }
    }


    @SuppressLint("NewApi")
    public void clearFocused() {
        if (focused != null) {
            focused.setForeground(getForegroundView());


        }
    }

    boolean isdashlineFrame;
    List<View> tiviews = new ArrayList<View>();
    List<ViewGroup> grviews = new ArrayList<ViewGroup>();

    //设置有id的控件 带白框
    private void visitViews(View userview, boolean isdashframe) {
        if (userview == null) {
            return;
        }
        if (userview.getId() != 0) {

//            if (selfimposed) {
//                setViewClickPanel(userview);
//            }
        }
//        userview.setEnabled(false);
        if (userview.getTag(R.id.uiflag) != null) {
            setViewClickPanel(userview);
        } else {
            if (userview instanceof TextView) {
                TextView tv = (TextView) userview;
                tv.setKeyListener(null);
//                if (!TextUtils.isEmpty(tv.getText()) || tv instanceof EditText) {
                setViewClickPanel(userview);
//                }
            } else if (userview instanceof ImageView) {

//                if (((ImageView) userview).getDrawable() != null) {
                setViewClickPanel(userview);

//                } else if (userview instanceof app.auto.runner.base.widget.ImageView && !TextUtils.isEmpty(((app.auto.runner.base.widget.ImageView) userview).getUrl())) {
//                    setViewClickPanel(userview);
//                }
            } else if (userview instanceof AdapterView||userview instanceof ViewGroup) {


            }else{
                setViewClickPanel(userview);
            }
        }
        if (userview instanceof ViewGroup) {
            grviews.add((ViewGroup) userview);
            for (int i = 0; i < ((ViewGroup) userview).getChildCount(); i++) {
                View view = ((ViewGroup) userview).getChildAt(i);

                visitViews(view, isdashframe);
            }

        }
        userview.setForeground(userview instanceof ViewGroup ? getForegroundGroup() : getForegroundView());
        setViewTouch(userview);

    }


    private void setViewClickPanel(final View userview) {

        tiviews.add(userview);
        userview.setFocusable(true);
        userview.setFocusableInTouchMode(true);
        userview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setFocused(view);
            }
        });
//        userview.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//
//                if (view != getCurrentFocus()) return false;
//                nextGroupFocus(((ViewGroup) ((View) userview).getParent()), false);
//                return false;
//            }
//
//        });
//            userview.setOnClickListener(new View.OnClickListener() {
//
//                public long secondClickTime;
//                public long firstClickTime;
//                public long mClickTime;
//
//                @Override
//                public void onClick(final View v) {
//
////                    if (System.currentTimeMillis() - mClickTime < 800) {
////                        //此处做双击具体业务逻辑
////                        if (v instanceof TextView || v instanceof android.widget.ImageView) {
////                            doubleClick_2.simpleRun(v);
////                        } else {
////
////                            clicktask(v, userview);
////                        }
////                            mClickTime = 0;
////                    } else {
////                        mClickTime = System.currentTimeMillis();
////                        //表示单击，此处也可以做单击的操作
////                        clicktask(v, userview);
////
////                    }
//
//
//                }
//            });

//            userview.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    if (!TextUtils.isEmpty((CharSequence) v.getTag(R.id.xml))) {
//                        ToastUtil.live((Activity) v.getContext()).toast(v.getTag(R.id.xml));
//                    }
//                    return false;
//                }
//            });
    }

    public void delAlert(final View view, boolean ifask) {
        if (view == null || view.getParent() == null) {
            return;
        }
        if (ifask) {
            ShareAlert.delAlert((Activity) view.getContext(), new FunCallback() {
                @Override
                public void simpleRun(Object aty) {
                    super.simpleRun(aty);
                    getView(R.id.nav).performClick();
                    ((ViewGroup) view.getParent()).removeView(view);
                    clearClickedView(view);

                }
            });
        } else {
            getView(R.id.nav).performClick();
            ((ViewGroup) view.getParent()).removeView(view);
            clearClickedView(view);
        }
    }

    public void delAlert(final View view) {
        delAlert(view, true);
    }

    public void clicktask(View userview) {
        setFocused(userview);
        clearfGroupFocused();
    }

    public Drawable getForegroundGroup() {
        return isdashlineFrame ? ContextCompat.getDrawable(ViewActivity.this, R.drawable.dashlinegroup) : new ColorDrawable(0x00000000);
    }

    public Drawable getForegroundView() {
        return isdashlineFrame ? ContextCompat.getDrawable(ViewActivity.this, R.drawable.dashlineview) : new ColorDrawable(0x00000000);
    }

    @SuppressLint("NewApi")
    public void setFocused(View focused) {
        if (this.focused != null) {
            this.focused.setForeground(focused instanceof ViewGroup ? getForegroundGroup() : getForegroundView());
//            ((View) this.focused.getParent()).setForeground(getForeground());

        }
        this.focused = focused;
        status(getTextView(R.id.status), focused);
    }

    private long[] mHits = new long[2];


    @SuppressLint({"NewApi", "ResourceType"})
    private void status(TextView status, View focused) {
        //处理标题
        String idx = "";
        String id = "";
        String childrencount = "";
        if (focused.getParent() != null) {
            idx = "[ " + (((ViewGroup) focused.getParent()).indexOfChild(focused) + 1) + "/" + ((ViewGroup) focused.getParent()).getChildCount() + " ]";
        }
        if (focused instanceof ViewGroup) {
            childrencount = " : " + ((ViewGroup) focused).getChildCount() + "";
        }

        if (focused.getId() > 0) {
            String v = RRes.getAttrValue_itsname().get(focused.getId());
            if (v != null) {
                id = v;
            }

        }
        id = id.equals("") ? "" : "   " + id + "  ";
        String name = focused.getClass().getSimpleName().replace("VIEW", "View").replace("LAYOUT", "Layout");
        String result = idx + " : " + name + id + childrencount;
        status.setText(result);
        func.setParam(focused);
        focused.setForeground(ContextCompat.getDrawable(ViewActivity.this, R.drawable.auto_background_rect_white));
//        ((View) focused.getParent()).setForeground(ContextCompat.getDrawable(R.drawable.auto_background_rect_yellow, null));
        if (isAttachToWindow) {

        }
    }

    PopupWindow attrPopupWd;


    @SuppressLint("NewApi")
    public View getCurrentFocus() {
        if (focused != null && focused.getForeground() != null) {
            return focused;
        } else if (focusedGroup != null && focusedGroup.getForeground() != null) {
            return focusedGroup;
        }
        return null;
    }

    @SuppressLint("NewApi")
    public void clearClickedView(View view) {
        if (view != null) {
            if (tiviews.indexOf(view) != -1) {
                tiviews.remove(view);
            }
        }
        if (view != null) {
            if (grviews.indexOf(view) != -1) {
                grviews.remove(view);
            }
        }
    }

    Boolean backflag = false;

    @Override
    public void onBackPressed() {


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        backexit();


        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {


            Toast.makeText(ViewActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            if (objfilepath != null) {

                turnWhile(getTopview(), saveas(objfilepath));

            }
            DialogUtil.cancelDialog();
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (objfilepath != null) {

            SPrefUtil.putValue(this, "filecontext", "currfile", objfilepath);
        }
    }
}
